package org.smartboot.flow.custom;

import org.smartboot.flow.core.EngineContext;
import org.smartboot.flow.core.common.ComponentType;
import org.smartboot.flow.core.component.Component;
import org.smartboot.flow.core.visitor.ComponentVisitor;

/**
 * @author qinluo
 * @date 2024-08-18 23:11:33
 * @since 1.0.0
 */
public class TransactionComponent<T, S> extends Component<T, S> {

    private Component<T, S> component;
    private TransactionManager transactionManager;

    @Override
    public int invoke(EngineContext<T, S> context) throws Throwable {
        return transactionManager.run(() -> {
            try {
                return component.invoke(context);
            } catch (Throwable e) {
                return 0;
            }
        });
    }

    @Override
    public void accept(ComponentVisitor visitor) {
        visitor.visitStandardAttributes(this.standardAttributes);
        visitor.visitNonStandardAttributes(this.nonStandardAttributes);
        visitor.visitSource(this);

        ComponentVisitor componentVisitor = visitor.visitComponent(component.getType(), component.getName(), component.getCode());
        if (componentVisitor != null) {
            component.accept(componentVisitor);
        }
        visitor.visitEnd();
    }

    @Override
    public ComponentType getType() {
        return ComponentType.CUSTOM;

    }

    @Override
    public void rollback(EngineContext<T, S> context) {
        component.rollback(context);
    }
}
